import { clearObject, deepCopyObj } from '../../../assets/js/help.js'
export default {
  data() {
    var validateParkNameList = (rule, value, callback) => {
      var self = this;
      if (!self.saveConfig.parkList) {
        return callback(new Error('请选择停车场'));
      }
      callback();
    };

    var validateValidTime = (rule, value, callback) => {
      if (value == null || value == '' || value == ',') {
        return callback(new Error('请选择有效日期'));
      }
      callback();
    };

    var validateConfigRule = (rule, value, callback) => {
      var self = this;
      if (!self.saveConfig.reliefRuleScore || !self.saveConfig.reliefRuleValue) {
        return callback(new Error('请填写抵扣规则'));
      }
      if (self.saveConfig.reliefRuleScore > 999999) {
        return callback(new Error('数值为 1 到 6 位'));
      }
      callback();
    };

    var validateMaxReliefValue = (rule, value, callback) => {
      var self = this;
      if (value === null || value === '') {
        return callback(new Error('单次最高抵扣积分不能为空'));
      }
      if (! /^[1-9]+[0-9]*$/.test(value)) {
        return callback(new Error('请输入大于0的积分'));
      }
      callback();
    };

    return {
      saveConfig: {
        id: '',
        configName: "",
        parkIds: "",
        inputParks: "",
        validTime: "",
        reliefRuleScore: "",
        maxReliefValue: "",
        reliefRuleValue: '',
        parkList: [],
        parkNameList: [],
        remark: '',
      },
      curParkList:[],
      handleStatu:0,//当前操作状态.默认编辑，1为新增
      configRules: {
        configName: [
          { required: true, message: '配置名称不能为空', trigger: 'change' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'change' }
        ],
        parkNameList: [
          { required: true, validator: validateParkNameList, trigger: 'change' }
        ],
        validTime: [
          { validator: validateValidTime, trigger: 'change' }
        ],
        configRule: [
          { validator: validateConfigRule, trigger: 'change' }
        ],
        maxReliefValue: [
          { validator: validateMaxReliefValue, trigger: 'change' },
          { min: 1, max: 6, message: '数值为 1 到 6 位', trigger: 'change' }
        ],
        // remark: [
        //   { max: 100, message: '最多100 个字符', trigger: 'change' }
        // ],
      }
    }
  },
  created() {
    
  },
  computed: {
    inputParkstr: function (val) {
      var park_arr = []
      if(this.saveConfig.parkNameList.length>0){
        park_arr = this.saveConfig.parkNameList.split(',')
        this.curParkList = park_arr
      }
      return park_arr.join("/")
    },
  },
  filters: {
    configStatus: function (val) {
      switch (val) {
        case 0:
          return "禁用"
        case 1:
          return "启用"
        default:
          break;
      }
    }
  },
  methods: {
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.list(params);
    },
    list(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.score.configList(params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        }, err => { })
    },
    toDisable(config) {
      var self = this;

      let params = {
        id: config.id,
        tips: 'FROZE'
      };
      self.showDialog("确认禁用该配置?", '', function () {
        API.score.configDisable(params).then(res => {
          self.showToast('操作成功', false);
          self.getList();
        }, err => { })
      });
    },//toDisable end
    toEnable(config) {
      var self = this;
      let params = {
        id: config.id,
        tips: 'VALID'
      };
      self.showDialog("确认启用该配置?", '', function () {
        API.score.configEnable(params).then(res => {
          self.showToast('操作成功', false);
          self.getList();
        }, err => { })
      });
    },//toEnable end
    toDel(config) {
      var self = this;
      let params = {
        id: config.id,
        tips: 'DEL'
      };
      self.showDialog("确认删除该配置?", '', function () {
        API.score.configDel(params).then(res => {
          self.showToast('操作成功', false);
          self.getList();
        }, err => { })
      });
    },//toDel end
    toAdd() {
      var self = this;
      self.handleStatu = 1
      clearObject(clearObject(self.saveConfig));
      self.toOpenModal('configModal', 1)

    },//toAdd end
    toEdit(config) {
      var self = this;
      self.handleStatu = 0
      self.saveConfig.validTime = [new Date(config.validFrom), new Date(config.validTo)];
      self.saveConfig.parkNameList = config.parkName;
      self.saveConfig.parkList = config.parkIds.split(',');
      self.saveConfig.configName = config.configName;
      self.saveConfig.inputParks = config.parkName;
      self.saveConfig.reliefRuleScore = config.reliefRuleScore;
      self.saveConfig.maxReliefValue = config.maxReliefValue;
      self.saveConfig.remark = config.remark;
      self.saveConfig.reliefRuleValue = config.reliefRuleValue;
      self.saveConfig.id = config.id;

      self.toOpenModal('configModal', 1)
    },
    toSelectPark() {
      var _self = this;
      _self.toOpenModal('selectParkModal', 2);
      this.initParkTree("ParkTree");
    },//toSelectPark end
    initParkTree(treeId) {
      var _self = this;
      // API.monthTicket.getParkTree({})
      API.fetchGet('/score/deduct/config/getParkingBaseDataTree.do', {})
        .then(res => {
          //start..
          var data = res;
          if (data != null) {
            var nodes = data.data;
            var jsonStr = JSON.stringify(nodes);

            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            nodes = JSON.parse(jsonStr);
            var settings = {
              check: {
                enable: true,
                chkStyle: "checkbox",
                radioType: "all"
              },
              // data: {
              //     simpleData: {
              //         enable: true
              //     }
              // },
              view: {
                showIcon: false,
                showLine: false,
              },
              callback: {
                onClick: function (event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                },
              }
            };
            $.fn.zTree.destroy("ParkTree");

            var treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
            var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
            // console.log(nodes)
            for (var i = 0; i < _self.saveConfig.parkList.length; i++) {
              var node = treeObj.getNodeByParam("value", _self.saveConfig.parkList[i]);
              if (node) {
                if (node.getParentNode() && !node.getParentNode().open) {
                  treeObj.expandNode(node.getParentNode(), true, true, true);
                }
                treeObj.checkNode(node, true, true);
              }
            }
            treeObj.expandAll(true);

          } else {
            _self.showToast('暂时没有停车场可选', 2, 3000);
          }
          //end..
        }, err => { })

    },
    selectParkSure() {
      var self = this,
        nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      var parkList = new Array();
      // 初始化表格显示数据以及提交的表格参数
      for (var i = 0; i < nodes.length; i++) {
        if (!nodes[i].isArea) {
          parkList.push(nodes[i]);
        }
      }
      if (parkList.length <= 0) {
        self.showToast('请选择一个停车场', 0);
        return;
      }
      self.saveConfig.parkList = [];
      var parkNameArr = [];
      for (var i = 0; i < parkList.length; i++) {
        self.saveConfig.parkList.push(parkList[i].value);
        parkNameArr.push(parkList[i].name);
      }
      self.saveConfig.parkNameList = parkNameArr.join(',');
      self.closed('selectParkModal', 2);
    },
    submit(formName) {
      var self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          self.save();
        } else {
          return false;
        }
      });
    },//submitSave end
    save() {
      var self = this;
      let params = deepCopyObj(self.saveConfig);

      params['validFrom'] = self.saveConfig.validTime[0].Format('yyyy-MM-dd hh:mm:ss');
      params['validTo'] = self.saveConfig.validTime[1].Format('yyyy-MM-dd hh:mm:ss');
      params['parkIds'] = self.saveConfig.parkList.join(',');
      if (!self.saveConfig.id) {
        API.score.configAdd(params).then(res => {
          callback();
        }, err => { })
      } else {
        API.score.configEdit(params).then(res => {
          callback();
        }, err => { })
      }
      function callback() {
        self.showToast('操作成功', false);
        self.getList();
        self.closed('configModal', 1)
      }
    }//save end
  }
}